<?php
namespace common\models;

use common\models\ar\UserShadow;
use Yii;
use common\models\ar\UserBrokers;
use yii\base\Model;

/**
 * Login form
 */
class LoginForm extends Model
{
    public $username;
    public $password;
    public $captcha;
    public $captchaFlag = true;

    private $_user;
    private $_username;
    private $_uid;//主账户ID

    /**
     * @inheritdoc
     */
    public function rules()
    {
        $rules = [
            // username and password are both required
            ['username', 'required', 'message' => '代理编号不能为空'],
            ['password', 'required', 'message' => '密码不能为空'],
        ];

        if ($this->captchaFlag) {
            $rules[] = ['captcha', 'required', 'message' => '验证码不能为空'];
            $rules[] = ['captcha', 'captcha', 'captchaAction' => 'login/captcha', 'message' => '验证码不正确'];
            $rules[] = ['password', 'validatePassword'];
        }
        return $rules;
    }

    /**
     * Validates the password.
     * This method serves as the inline validation for password.
     *
     * @param string $attribute the attribute currently being validated
     * @param array $params the additional name-value pairs given in the rule
     */
    public function validatePassword($attribute, $params)
    {

        if (!$this->hasErrors()) {
            $user = $this->getUser();
            if (!$user || !$user->validatePassword($this->password)) {
                $this->addError($attribute, '账号或密码不正确');
            }
        }
    }

    /**
     * Logs in a user using the provided username and password.
     *
     * @return bool whether the user is logged in successfully
     */
    public function login()
    {
        if (!$this->hasErrors()) {
            $bool = Yii::$app->user->login($this->getUser());
            if ($bool) {
                $session = Yii::$app->getSession();
                if ($this->_user) {
                    $session->set('username', $this->_username);
                    $session->set('uid', $this->_uid);
                }
            }
            return $bool;
        } else {
            return false;
        }
    }

    /**
     * @return UserAgentIdentity|array|null|\yii\db\ActiveRecord
     */
    protected function getUser()
    {
        if ($this->_user === null) {
            $sql = "SELECT * FROM `user_brokers` WHERE `loginName` = :loginName";
            $this->_user = UserAgentIdentity::findBySql($sql, [':loginName' => $this->username])->one();
            if ($this->_user) {
                $this->_username = $this->_user->accountName;
                $this->_uid = $this->_user->loginName;
            }
        }
        return $this->_user;
    }
}
